package com.study.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author chenyeqing
 * @date 2021/11/24 22:42
 */
@Configuration
public class RabbitmqConfig {
    public static final String QUEUE_EMAIL = "queue_email";

    public static final String QUEUE_SMS = "queue_sms";

    public static final String EXCHANGE_NAME = "topic.exchange";

    public static final String ROUTING_KEY_EMAIL = "topic.#.email.#";

    public static final String ROUTING_KEY_SMS = "topic.#.sms.#";


    @Bean(EXCHANGE_NAME)
    public Exchange exchange() {
        // durable(true) 持久化，MQ重启后交换机还在
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }

    /**
     * 声明email队列
     * new Queue(QUEUE_EMAIL, true, false, false)
     * durable="true" 持久化 rabbitmq重启的时候不需要创建新的队列
     * auto-delete 表示消息队列没有在使用时将被自动删除，默认是false
     * exclusive 表示该消息队列是否只在当前connection生效，默认是false
     * @return
     */
    @Bean(QUEUE_EMAIL)
    public Queue emailQueue() {
        return new Queue(QUEUE_EMAIL);
    }

    @Bean(QUEUE_SMS)
    public Queue smsQueue() {
        return new Queue(QUEUE_SMS);
    }

    /**
     * ROUTING_KEY_EMAIL队列绑定交换机，指定routingKey
     * @param queue
     * @param exchange
     * @return
     */
    @Bean
    public Binding bindingEmail(@Qualifier(QUEUE_EMAIL) Queue queue,
                                @Qualifier(EXCHANGE_NAME) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY_EMAIL).noargs();
    }

    @Bean
    public Binding bindingSms(@Qualifier(QUEUE_SMS) Queue queue,
                              @Qualifier(EXCHANGE_NAME) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY_SMS).noargs();
    }
}
